/* 
 * File:   DefaultHttpServletFactory.cpp
 * Author: dell
 * 
 * Created on 2012年4月2日, 上午10:42
 */
#include <vector>
#include <string.h>
#include "RapidHttpServletFactory.h"
#include "ErrorHttpServlet.h"
#include "RapidHttpServlet.h"

using namespace std;

namespace Rapid{

    RapidHttpServletFactory::RapidHttpServletFactory(ServerConfig* serverConfig):serverConfig(serverConfig) {
    }

    RapidHttpServletFactory::~RapidHttpServletFactory() {
    }

    HttpServlet* RapidHttpServletFactory::create(const char* path){
        LOG_DEBUG("path:%s", path);

        int pathlen = strlen(path);
        char* rootend = strchr((char*)path+1, '/');
        const char* subpath;

        //计算根和子路径
        if(rootend){
            root.assign(path, rootend-path);
            subpath = rootend+1;
        }else{
            root.assign(path);
            subpath = path+pathlen;
        }


        LOG_DEBUG("root:%s, subpath:%s, subpath.size():%d", root.c_str(), subpath, strlen(subpath));
        LOG_DEBUG("serverConfig->contextConfigMap.size():%d", serverConfig->contextConfigMap.size());
        ServerConfig::ContextConfigMap::iterator cxtit = serverConfig->contextConfigMap.find(root.c_str());
        if(cxtit != serverConfig->contextConfigMap.end()){
            return servlet(serverConfig, cxtit->second, subpath);
        }else{
            cxtit = serverConfig->contextConfigMap.find("/");
            if(cxtit != serverConfig->contextConfigMap.end()){
                return servlet(serverConfig, cxtit->second, path+1);
            }else{
                LOG_WARN("context name \"%s\" not find", root.c_str());
                return error(400, "context name not find");
            }
        }

    }

    void RapidHttpServletFactory::free(HttpServlet* servlet){
            delete servlet;
    }

    
    HttpServlet* RapidHttpServletFactory::servlet(ServerConfig* serverConfig, ContextConfig* contextConfig, const char* subpath){
        return new RapidHttpServlet(serverConfig, contextConfig, subpath);
    }


    HttpServlet* RapidHttpServletFactory::error(unsigned short int code, const char* message){
        return new ErrorHttpServlet(code, message);
    }
    
}
